<template>
  <section id="match" class="py-16 bg-gray-50">
    <div class="container mx-auto px-4">
      <!-- 添加返回主页按钮 -->
      <!-- 返回主页按钮（右上角） -->
      <div class="back-home-container mb-6">
        <a-button @click="goToHomePage" class="back-home-btn">
          <i class="fa fa-home mr-2"></i>返回主页
        </a-button>
      </div>
      <div class="text-center mb-12" style="text-align: center;">
        <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold mb-4 text-primary"
          style="font-size: 30px; font-weight: bold;">组队大厅</h2>
        <p class="text-gray-600 max-w-2xl mx-auto" style="font-size: 16px; color: #666;">通过多种方式找到适合你的学习小组，一起进步</p>
      </div>

      <!-- 轮播图部分 -->
      <div class="carousel-section mb-12">
        <a-carousel autoplay class="custom-carousel" :autoplaySpeed="5000" dots dotPosition="bottom">
          <div class="carousel-item">
            <img src="https://images.unsplash.com/photo-1522202176988-66273c2fd55f?w=1200&h=400&fit=crop&crop=center"
              alt="团队协作学习" class="carousel-image">
            <div class="carousel-content">
              <h3>开启你的学习之旅</h3>
              <p>找到志同道合的伙伴，一起进步成长</p>
            </div>
          </div>
          <div class="carousel-item">
            <img src="https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=1200&h=400&fit=crop&crop=center"
              alt="编程学习" class="carousel-image">
            <div class="carousel-content">
              <h3>AI智能匹配</h3>
              <p>基于你的学习偏好，推荐最适合的战队</p>
            </div>
          </div>
          <div class="carousel-item">
            <img src="https://images.unsplash.com/photo-1552664730-d307ca884978?w=1200&h=400&fit=crop&crop=center"
              alt="团队讨论" class="carousel-image">
            <div class="carousel-content">
              <h3>团队协作学习</h3>
              <p>在团队中互相监督，共同提升技能</p>
            </div>
          </div>
        </a-carousel>
      </div>

      <!-- 战队卡片部分 -->
      <div class="teams-section">
        <div class="flex justify-between items-center mb-8">
          <h3 class="text-2xl font-bold text-gray-800">热门战队</h3>
          <div class="flex gap-3">
            <a-space size="large">
              <a-button type="primary" @click="openCreateTeamModal" class="create-team-btn">
                <i class="fa fa-plus mr-2"></i>创建战队
              </a-button>
              <a-button type="primary" @click="refreshTeams" class="refresh-btn">
                <i class="fa fa-refresh mr-2"></i>刷新
              </a-button>
              <a-button type="primary" @click="openMyTeamsModal" class="my-teams-btn">
                <i class="fa fa-users mr-2"></i>我的战队
              </a-button>
            </a-space>
          </div>
        </div>

        <!-- 搜索筛选区域 -->
        <div class="search-filter-section mb-6">
          <div class="search-filter-container">
            <div class="search-input-group">
              <a-input v-model:value="searchKeyword" placeholder="搜索战队名称" class="search-input"
                @keyup.enter="handleSearch">
                <template #prefix>
                  <i class="fa fa-search text-gray-400"></i>
                </template>
              </a-input>
            </div>

            <div class="filter-group">
              <a-select v-model:value="filterReviewStatus" placeholder="审核状态" class="filter-select"
                @change="handleSearch">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="0">无需审核</a-select-option>
                <a-select-option value="1">需要审核</a-select-option>
              </a-select>
            </div>

            <div class="action-group">
              <a-button type="primary" @click="handleSearch" class="search-btn">
                <i class="fa fa-search mr-2"></i>搜索
              </a-button>
              <a-button @click="resetSearch" class="reset-btn">
                <i class="fa fa-refresh mr-2"></i>重置
              </a-button>
            </div>
          </div>
        </div>

        <!-- 搜索结果统计 -->
        <div class="search-result-info mb-4" v-if="searchKeyword || filterReviewStatus">
          <span class="text-gray-600">
            找到 <span class="text-primary font-semibold">{{ teams.length }}</span> 个战队
            <span v-if="searchKeyword" class="ml-2">关键词: "{{ searchKeyword }}"</span>
            <span v-if="filterReviewStatus" class="ml-2">审核状态: {{ filterReviewStatus === '0' ? '无需审核' : '需要审核' }}</span>
          </span>
        </div>

        <a-row :gutter="[24, 24]">
          <a-col :xs="24" :sm="12" :md="6" v-for="team in teams" :key="team.id" v-loading="loading">
            <a-card hoverable class="team-card" @click="viewTeamDetail(team.id)">
              <template #cover>
                <div class="team-logo-container">
                  <img :src="getTeamLogoUrl(team.logo)" :alt="team.teamName" class="team-logo"
                    @error="handleImageError">
                  <div class="team-overlay">
                    <a-button type="primary" size="small" @click.stop="joinTeam(team.id)"
                      :loading="joiningTeamIds.has(team.id) || applyingTeamIds.has(team.id)"
                      :disabled="joiningTeamIds.has(team.id) || applyingTeamIds.has(team.id)">
                      {{ joiningTeamIds.has(team.id) ? '加入中...' : applyingTeamIds.has(team.id) ? '申请中...' : '加入战队' }}
                    </a-button>
                  </div>
                </div>
              </template>

              <div class="team-info">
                <h4 class="team-name">{{ team.teamName }}</h4>
                <p class="team-creator">队长: {{ team.captainName }}</p>

                <div class="team-meta">
                  <a-tag :color="team.needReview === 1 ? 'orange' : 'green'" class="review-tag">
                    {{ team.needReview === 1 ? '需要审核' : '无需审核' }}
                  </a-tag>
                  <span class="member-count">{{ team.currentCount }}/{{ team.maxCount }}人</span>
                </div>

                <div class="team-tags">
                  <a-tag v-for="tag in team.tagList" :key="tag" color="blue" class="team-tag">
                    {{ tag }}
                  </a-tag>
                </div>
                <p class="team-description">{{ team.description }}</p>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
      <a-pagination :current="page" :pageSize="pageSize" :total="total" @change="handlePageChange"
        show-size-changer="false" style="margin-top: 24px; text-align: center;" />
    </div>

    <!-- 创建战队弹窗 -->
    <a-modal v-model:open="showCreateTeamModal" title="创建战队" width="600px" :confirm-loading="createTeamLoading"
      @ok="handleCreateTeam" @cancel="closeCreateTeamModal" ok-text="创建" cancel-text="取消">
      <div class="create-team-form">
        <div class="form-item">
          <label class="form-label">战队名称 <span class="required">*</span></label>
          <a-input v-model:value="createTeamForm.teamName" placeholder="请输入战队名称" maxlength="50" show-count />
        </div>

        <div class="form-item">
          <label class="form-label">战队描述 <span class="required">*</span></label>
          <a-textarea v-model:value="createTeamForm.description" placeholder="请输入战队描述" :rows="4" maxlength="200"
            show-count />
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">战队Logo</label>
            <div class="logo-upload-container">
              <a-upload :before-upload="handleLogoUpload" :show-upload-list="false" accept="image/*">
                <div class="logo-upload-area">
                  <div v-if="!logoPreview" class="logo-upload-placeholder">
                    <i class="fa fa-cloud-upload" style="font-size: 24px; color: #999;"></i>
                    <p style="margin: 8px 0 0 0; color: #999;">点击上传Logo</p>
                    <p style="margin: 4px 0 0 0; font-size: 12px; color: #ccc;">支持 JPG、PNG、GIF、WebP 格式，小于 2MB</p>
                  </div>
                  <img v-else :src="logoPreview" alt="Logo预览" class="logo-preview" />
                </div>
              </a-upload>
              <div v-if="uploadLoading" class="upload-loading">
                <i class="fa fa-spinner fa-spin"></i> 上传中...
              </div>
            </div>
          </div>

          <div class="form-item">
            <label class="form-label">最大人数</label>
            <a-input-number v-model:value="createTeamForm.maxCount" :min="1" :max="100" style="width: 100%" />
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">标签</label>
          <a-select v-model:value="selectedTags" mode="multiple" placeholder="请选择标签" style="width: 100%"
            @change="handleTagChange">
            <a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id">
              {{ tag.tagName }}
            </a-select-option>
          </a-select>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">是否需要审核</label>
            <a-select v-model:value="createTeamForm.needReview" style="width: 100%">
              <a-select-option :value="0">无需审核</a-select-option>
              <a-select-option :value="1">需要审核</a-select-option>
            </a-select>
          </div>

          <div class="form-item">
            <label class="form-label">是否需要订阅</label>
            <a-select v-model:value="createTeamForm.isSubscribe" style="width: 100%">
              <a-select-option :value="0">免费</a-select-option>
              <a-select-option :value="1">付费</a-select-option>
            </a-select>
          </div>
        </div>

        <div v-if="createTeamForm.isSubscribe === 1" class="subscription-settings">
          <div class="form-row">
            <div class="form-item">
              <label class="form-label">订阅价格</label>
              <a-input-number v-model:value="createTeamForm.subscribePrice" :min="0" :precision="2"
                style="width: 100%" />
            </div>

            <div class="form-item">
              <label class="form-label">订阅周期</label>
              <a-select v-model:value="createTeamForm.subscribeCycle" style="width: 100%">
                <a-select-option :value="0">无</a-select-option>
                <a-select-option :value="1">周</a-select-option>
                <a-select-option :value="2">月</a-select-option>
                <a-select-option :value="3">季</a-select-option>
                <a-select-option :value="4">年</a-select-option>
              </a-select>
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label class="form-label">订阅折扣</label>
              <a-input-number v-model:value="createTeamForm.subscribeDiscount" :min="0" :max="1" :step="0.1"
                :precision="1" style="width: 100%" />
            </div>

            <div class="form-item">
              <label class="form-label">试用天数</label>
              <a-input-number v-model:value="createTeamForm.trialDays" :min="0" style="width: 100%" />
            </div>
          </div>

          <div class="form-item">
            <label class="form-label">自动续费</label>
            <a-select v-model:value="createTeamForm.autoRenew" style="width: 100%">
              <a-select-option :value="0">否</a-select-option>
              <a-select-option :value="1">是</a-select-option>
            </a-select>
          </div>
        </div>
      </div>
    </a-modal>


    <!-- 我的战队弹窗组件 -->
    <my-teams :visible="showMyTeamsModal" @update:visible="(visible) => showMyTeamsModal = visible" />

    <!-- 申请加入战队弹窗 -->
    <a-modal v-model:open="showJoinTeamModal" title="申请加入战队" width="500px" :confirm-loading="joinTeamLoading"
      @ok="handleJoinTeam" @cancel="closeJoinTeamModal" ok-text="提交申请" cancel-text="取消">
      <div class="join-team-form">
        <div class="team-info-preview mb-4">
          <div class="flex items-center space-x-3">
            <img :src="getTeamLogoUrl(selectedTeam?.logo)" :alt="selectedTeam?.teamName"
              class="w-12 h-12 rounded-lg object-cover" @error="handleImageError">
            <div>
              <h4 class="text-lg font-semibold text-gray-800">{{ selectedTeam?.teamName }}</h4>
              <p class="text-sm text-gray-600">队长: {{ selectedTeam?.captainName }}</p>
            </div>
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">申请理由 <span class="required">*</span></label>
          <a-textarea v-model:value="joinTeamForm.reason" placeholder="请简要说明申请加入该战队的原因..." :rows="4" maxlength="200"
            show-count />
        </div>

        <!-- <div class="form-item">
          <label class="form-label">联系方式</label>
          <a-input
            v-model:value="joinTeamForm.contact"
            placeholder="请输入您的联系方式（QQ、微信等）"
            maxlength="50"
          />
        </div> -->

        <!-- <div class="form-item">
          <label class="form-label">技能标签</label>
          <a-select
            v-model:value="joinTeamForm.skills"
            mode="multiple"
            placeholder="请选择您擅长的技能"
            style="width: 100%"
          >
            <a-select-option
              v-for="tag in tagList"
              :key="tag.id"
              :value="tag.id"
            >
              {{ tag.tagName }}
            </a-select-option>
          </a-select>
        </div> -->

        <!-- <div class="notice-info">
          <a-alert
            message="申请提示"
            description="您的申请将提交给战队管理员审核，审核通过后您将收到通知。"
            type="info"
            show-icon
          />
        </div> -->
      </div>
    </a-modal>
  </section>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Carousel, Card, Button, Tag, message, Modal, Input, Textarea, InputNumber, Select, SelectOption, Upload, Alert } from 'ant-design-vue';
import { getTeamList, findJoinedTeams, createTeam, applyJoinTeam, getTeamListWithCaptain,getTeamMembersCount } from '@/api/sysTeamController';
import { getTagList } from '@/api/sysTagController';
import { uploadPic } from '@/api/bizMediaFileController';
import { getMinioUrl, validateImageFile, config } from '@/utils/config';
// import MyTeams from '@/components/teamlearning/MyTeams.vue';

//初始化路由
const router = useRouter();

// 用户信息相关 - 直接在组件中实现
const userInfo = ref(null);
// 新增状态管理
const showMyTeamsModal = ref(false);
// 检查用户登录状态
const checkUserLogin = () => {
  try {
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      const userInfo = JSON.parse(storedUserInfo)
      console.log('MatchSection - 当前登录用户信息:', userInfo)
      return userInfo
    } else {
      console.log('MatchSection - 用户未登录')
      return null
    }
  } catch (error) {
    console.error('检查用户登录状态失败:', error)
    return null
  }
}

// 获取当前用户ID - 等效于 StpUtil.getLoginIdAsInt()
const getLoginIdAsInt = () => {
  const userInfo = checkUserLogin()
  if (userInfo && userInfo.userId) {
    return parseInt(userInfo.userId)
  }
  return null
}

// 战队数据
const teams = ref([]);
const allTeams = ref([]); // 保存所有战队数据
const filteredTeams = ref([]); // 筛选后的战队数据
const loading = ref(false);
const page = ref(1);
const pageSize = ref(8);
const total = ref(0);

// 搜索筛选相关
const searchKeyword = ref('');
const filterReviewStatus = ref('');

// 创建战队相关
const showCreateTeamModal = ref(false);
const createTeamForm = ref({
  teamName: '',
  description: '',
  logo: '',
  tag: '',
  maxCount: 20,
  needReview: 0,
  isSubscribe: 0,
  subscribePrice: 0,
  subscribeCycle: 0,
  subscribeDiscount: 1,
  trialDays: 0,
  autoRenew: 0
});
const createTeamLoading = ref(false);

// 标签相关
const tagList = ref([]);
const selectedTags = ref([]);

// 图片上传相关
const logoFile = ref(null);
const logoPreview = ref('');
const uploadLoading = ref(false);

// 申请加入战队相关
const showJoinTeamModal = ref(false);
const joinTeamLoading = ref(false);
const selectedTeam = ref(null);
const joinTeamForm = ref({
  reason: '',
  contact: '',
  skills: []
});

// 防止重复点击加入战队的状态管理
const joiningTeamIds = ref(new Set()); // 记录正在加入的战队ID
const applyingTeamIds = ref(new Set()); // 记录正在申请的战队ID


// 修改"我的战队"按钮点击事件
const openMyTeamsModal = () => {
  showMyTeamsModal.value = true;
};

// 获取标签列表
const fetchTagList = async () => {
  try {
    const response = await getTagList();

    if (response.data.code === 0) {
      tagList.value = response.data.data;
    } else {
      console.error('获取标签列表失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取标签列表失败：', error);
    // 如果API调用失败，使用模拟数据
    tagList.value = [
      { id: 1, tagName: 'Java', tagType: 1 },
      { id: 2, tagName: 'Python', tagType: 1 },
      { id: 3, tagName: 'Vue', tagType: 1 },
      { id: 4, tagName: 'JS', tagType: 1 },
      { id: 5, tagName: 'Spring', tagType: 1 },
      { id: 6, tagName: 'SpringBoot', tagType: 1 },
      { id: 7, tagName: 'SpringCloud', tagType: 1 }
    ];
    console.log('使用模拟标签数据:', tagList.value);
  }
};

function shuffleArray(array) {
  const arr = [...array];
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

// 获取战队列表
const fetchTeams = async () => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录后再查看战队');
    return;
  }

  loading.value = true;
  try {
    // 并行获取两个接口的数据
    const [membersCountRes, captainInfoRes] = await Promise.all([
      getTeamMembersCount({
        current: page.value,
        pageSize: pageSize.value
      }),
      getTeamListWithCaptain({
        current: page.value,
        pageSize: pageSize.value
      })
    ]);

    // 检查接口状态
    if (captainInfoRes.data.code !== 0 || membersCountRes.data.code !== 0) {
      throw new Error(captainInfoRes.data.message || membersCountRes.data.message || '获取战队列表失败');
    }

    // 创建人数映射表
    const countMap = {};
    membersCountRes.data.data.records.forEach(team => {
      countMap[team.id] = team.currentCount;
    });

    // 处理最终数据
    const processedTeams = captainInfoRes.data.data.list.map(team => {
      // 处理标签显示
      const tagList = team.tag
        ? team.tag.split(',')
          .filter(tag => tag.trim())
          .map(tag => {
            // 如果有标签ID到名称的映射，可以在这里转换
            return tag.trim();
          })
        : [];

      return {
        ...team,
        tagList,
        captainName: team.username || `用户${team.creatorId}`, // 使用username作为队长名称
        currentCount: countMap[team.id] || 0, // 使用countMap中的人数
        needReview: team.needReview,
        maxCount: team.maxCount
      };
    });

    teams.value = shuffleArray(processedTeams);
    filteredTeams.value = [...processedTeams];
    total.value = captainInfoRes.data.data.total;

  } catch (error) {
    console.error('战队数据加载失败:', error);
    message.error(error.message);
    // 使用模拟数据作为fallback
    teams.value = shuffleArray(getMockTeams());
    filteredTeams.value = [...teams.value];
    total.value = teams.value.length;
  } finally {
    loading.value = false;
  }
};

// 搜索和筛选方法
const handleSearch = async () => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录后再搜索战队');
    return;
  }
  
  page.value = 1;
  loading.value = true;
  try {
    // 构造搜索参数
    const searchParams = {
      current: page.value,
      pageSize: pageSize.value
    };
    
    if (searchKeyword.value.trim()) {
      searchParams.teamName = searchKeyword.value.trim();
    }
    if (filterReviewStatus.value !== '') {
      searchParams.needReview = parseInt(filterReviewStatus.value);
    }

    // 并行获取两个接口的数据
    const [membersCountRes, captainInfoRes] = await Promise.all([
      getTeamMembersCount(searchParams),
      getTeamListWithCaptain(searchParams)
    ]);

    if (captainInfoRes.data.code !== 0 || membersCountRes.data.code !== 0) {
      throw new Error(captainInfoRes.data.message || membersCountRes.data.message || '搜索战队失败');
    }

    // 创建人数映射表
    const countMap = {};
    membersCountRes.data.data.records.forEach(team => {
      countMap[team.id] = team.currentCount;
    });

    // 处理搜索结果
    const processedTeams = captainInfoRes.data.data.list.map(team => ({
      ...team,
      tagList: team.tag ? team.tag.split(',').filter(t => t.trim()) : [],
      captainName: team.username || `用户${team.creatorId}`,
      currentCount: countMap[team.id] || 0
    }));

    teams.value = shuffleArray(processedTeams);
    filteredTeams.value = teams.value;
    total.value = captainInfoRes.data.data.total;

    if (processedTeams.length === 0) {
      message.info('没有找到匹配的战队');
    } else {
      message.success(`找到 ${processedTeams.length} 个战队`);
    }
  } catch (error) {
    console.error('搜索战队失败：', error);
    message.error(error.message);
    // 使用本地筛选作为fallback
    handleLocalSearch();
  } finally {
    loading.value = false;
  }
};

const goToHomePage = () => {
  // 主页路由路径，根据实际情况修改（通常是 '/' 或 '/home'）
  router.push('/');
};

// 重置搜索
const resetSearch = async () => {
  searchKeyword.value = '';
  filterReviewStatus.value = '';

  // 重置到第一页
  page.value = 1;

  // 重新获取所有战队数据
  await fetchTeams();
  message.success('搜索条件已重置');
};

// 刷新战队列表
const refreshTeams = () => {
  // 只打乱当前页的teams
  teams.value = shuffleArray([...teams.value]);
  message.success('战队顺序已随机刷新');
};

// 查看战队详情
const viewTeamDetail = (teamId) => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录后再查看战队详情');
    return;
  }
  console.log(`用户ID ${userId} 查看战队详情，战队ID: ${teamId}`);
  router.push({ path: '/team', query: { teamId: teamId } });
};

// 加入战队
const joinTeam = async (teamId) => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录后再加入战队');
    return;
  }

  const team = teams.value.find(t => t.id === teamId);
  if (!team) {
    message.error('战队不存在');
    return;
  }

  if (team.currentCount >= team.maxCount) {
    message.warning('战队人数已满');
    return;
  }

  // 检查是否正在加入该战队
  if (joiningTeamIds.value.has(teamId)) {
    message.warning('正在加入战队，请稍候...');
    return;
  }

  // 根据战队是否需要审核来决定处理方式
  if (team.needReview === 1) {
    // 需要审核，弹出申请框
    selectedTeam.value = team;
    showJoinTeamModal.value = true;
  } else {
    // 无需审核，直接调用接口加入
    joiningTeamIds.value.add(teamId); // 标记正在加入
    try {
      const params = {
        id: 0,
        teamId: teamId,
        userId: userId,
        role: 0,
        joinType: 0,
        joinTime: "",
        status: 0, // 0: 无需审核，直接加入
        inviterId: 0,
        quitReason: "",
        auditTime: "",
        auditorId: 0,
        remark: "直接加入战队",
        createTime: "",
        updateTime: "",
        deleted: 0
      };

      const res = await applyJoinTeam(params);
      if (res.data.code === 0) {
        message.success('已成功加入战队');
        team.currentCount++;
        await fetchTeams(); // 刷新战队列表
      } else {
        message.error(res.data.message || '您已加入此战队，请不要重复加入');
      }
    } catch (error) {
      console.error('加入战队失败：', error);
      message.error('加入战队失败，请稍后重试');
    } finally {
      joiningTeamIds.value.delete(teamId); // 移除标记
    }
  }
};

// 提交申请加入战队
const handleJoinTeam = async () => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录后再申请加入战队');
    return;
  }

  if (!joinTeamForm.value.reason.trim()) {
    message.warning('请输入申请理由');
    return;
  }
  if (!selectedTeam.value || !selectedTeam.value.id) {
    message.warning('请选择要加入的战队');
    return;
  }

  const teamId = selectedTeam.value.id;

  // 检查是否正在申请该战队
  if (applyingTeamIds.value.has(teamId)) {
    message.warning('正在申请加入战队，请稍候...');
    return;
  }

  const params = {
    id: 0,
    teamId: teamId,
    userId: userId,
    role: 0,
    joinType: 0,
    joinTime: "",
    status: 1, // 1: 待审核
    inviterId: 0,
    quitReason: "",
    auditTime: "",
    auditorId: 0,
    remark: joinTeamForm.value.reason,
    createTime: "",
    updateTime: "",
    deleted: 0
  };
  console.log('申请参数', params);

  joinTeamLoading.value = true;
  applyingTeamIds.value.add(teamId); // 标记正在申请
  try {
    const res = await applyJoinTeam(params);
    //添加发送请求
    // 判断res.data.code是否为0，如果为0，则申请成功，否则申请失败
    if (res.data.code === 0) {
      message.success('申请已提交，请等待审核');
      showJoinTeamModal.value = false;
      await fetchTeams();
    } else {
      message.error(res.data.message);
    }
  } catch (error) {
    message.error('申请加入战队失败，请稍后重试');
  } finally {
    joinTeamLoading.value = false;
    applyingTeamIds.value.delete(teamId); // 移除标记
  }
};

// 关闭申请加入战队弹窗
const closeJoinTeamModal = () => {
  showJoinTeamModal.value = false;
  selectedTeam.value = null; // 清空选中的战队
  joinTeamForm.value = {
    reason: '',
    contact: '',
    skills: []
  };
  // 清空申请状态
  if (selectedTeam.value) {
    applyingTeamIds.value.delete(selectedTeam.value.id);
  }
};

// 创建战队
const handleCreateTeam = async () => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录后再创建战队');
    return;
  }

  if (!createTeamForm.value.teamName.trim()) {
    message.warning('请输入战队名称');
    return;
  }

  if (!createTeamForm.value.description.trim()) {
    message.warning('请输入战队描述');
    return;
  }

  createTeamLoading.value = true;
  try {
    const response = await createTeam({
      ...createTeamForm.value,
      creatorId: userId,
      createBy: userId,
      updateBy: userId
    });

    if (response.data.code === 0) {
      message.success('战队创建成功！');
      showCreateTeamModal.value = false;
      // 重置表单
      createTeamForm.value = {
        teamName: '',
        description: '',
        logo: '',
        tag: '',
        maxCount: 20,
        needReview: 0,
        isSubscribe: 0,
        subscribePrice: 0,
        subscribeCycle: 0,
        subscribeDiscount: 1,
        trialDays: 0,
        autoRenew: 0
      };
      // 刷新战队列表
      await fetchTeams();
    } else {
      message.error(response.data.msg || '创建战队失败');
    }
  } catch (error) {
    message.error('创建战队失败，请稍后重试');
  } finally {
    createTeamLoading.value = false;
  }
};

// 打开创建战队弹窗
const openCreateTeamModal = () => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录后再创建战队');
    return;
  }
  showCreateTeamModal.value = true;
};

// 图片上传处理
const handleLogoUpload = async (file) => {
  // 使用配置文件验证图片
  const validation = validateImageFile(file);
  if (!validation.valid) {
    message.error(validation.message);
    return false;
  }

  logoFile.value = file;
  logoPreview.value = URL.createObjectURL(file);

  // 上传图片到MinIO
  uploadLoading.value = true;
  try {
    const response = await uploadPic({}, file);
    if (response.data.code === 0) {
      // 获取MinIO的图片URL
      const uploadResult = response.data.data;
      // 根据MinIO配置构建完整的图片URL
      const imageUrl = uploadResult.filePath || uploadResult.url;
      createTeamForm.value.logo = imageUrl;
      message.success('图片上传成功！');
    } else {
      message.error(response.data.message || '图片上传失败');
    }
  } catch (error) {
    message.error('图片上传失败，请稍后重试');
  } finally {
    uploadLoading.value = false;
  }

  return false; // 阻止默认上传行为
};

// 标签选择处理
const handleTagChange = (values) => {
  selectedTags.value = values;
  // 将选中的标签ID转换为逗号分隔的字符串
  createTeamForm.value.tag = values.join(',');
};

// 获取战队Logo URL
const getTeamLogoUrl = (logo) => {
  const url = getMinioUrl(logo);
  return url;
};

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = config.image.defaultLogo;
};

// 关闭创建战队弹窗
const closeCreateTeamModal = () => {
  showCreateTeamModal.value = false;
  // 重置表单
  createTeamForm.value = {
    teamName: '',
    description: '',
    logo: '',
    tag: '',
    maxCount: 20,
    needReview: 0,
    isSubscribe: 0,
    subscribePrice: 0,
    subscribeCycle: 0,
    subscribeDiscount: 1,
    trialDays: 0,
    autoRenew: 0
  };
  // 重置图片和标签
  logoFile.value = null;
  logoPreview.value = '';
  selectedTags.value = [];
};

const handlePageChange = (newPage) => {
  console.log(`切换到第 ${newPage} 页`);
  page.value = newPage;
  fetchTeams();
};

// 组件挂载时检查用户登录状态并获取战队列表
onMounted(() => {
  console.log('MatchSection 组件挂载开始...');
  userInfo.value = checkUserLogin();
  console.log('用户信息:', userInfo.value);
  fetchTeams();
  fetchTagList();
  console.log('MatchSection 组件挂载完成');
});
</script>

<style scoped>
:root {
  --primary: #165DFF;
  --success: #00B42A;
}

.container {
  max-width: 1500px;
  margin-left: auto;
  margin-right: auto;
  padding-left: 2rem;
  padding-right: 2rem;
}

/* 轮播图样式 */
.carousel-section {
  margin-bottom: 3rem;
}

.custom-carousel {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

:deep(.ant-carousel .slick-dots) {
  bottom: 20px;
}

:deep(.ant-carousel .slick-dots li button) {
  background: rgba(255, 255, 255, 0.5);
  border-radius: 50%;
  width: 12px;
  height: 12px;
}

:deep(.ant-carousel .slick-dots li.slick-active button) {
  background: #165DFF;
}

.carousel-item {
  position: relative;
  height: 400px;
}


.my-teams-btn {
  background: #722ED1 !important;
  border-color: #722ED1 !important;
  color: #fff !important;
  transition: all 0.3s ease;
}

.my-teams-btn:hover {
  background: #5a1db1 !important;
  border-color: #5a1db1 !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(114, 46, 209, 0.2);
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  padding: 2rem;
  text-align: center;
}

.carousel-content h3 {
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.carousel-content p {
  font-size: 1rem;
  opacity: 0.9;
}

.back-home-container {
  text-align: right;
  /* 右对齐 */
}

.back-home-btn {
  background-color: #f0f2f5 !important;
  color: #333 !important;
  border: none !important;
  transition: all 0.2s ease;
  /* 可选：添加轻微阴影增强层次感 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.back-home-btn:hover {
  background-color: #e5e6eb !important;
  transform: translateY(-2px);
  /* 上移效果 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 确保按钮不会与其他元素重叠 */
@media (max-width: 768px) {
  .back-home-container {
    margin-bottom: 12px;
  }
}

/* 搜索筛选区域样式 */
.search-filter-section {
  background: #fff;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
}

.search-filter-container {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.search-input-group {
  flex: 1;
  min-width: 250px;
}

.search-input {
  width: 100%;
}

.filter-group {
  min-width: 150px;
}

.filter-select {
  width: 100%;
}

.action-group {
  display: flex;
  gap: 0.5rem;
  flex-shrink: 0;
}

.search-btn {
  background: #165DFF;
  border-color: #165DFF;
}

.search-btn:hover {
  background: #0e4bcc;
  border-color: #0e4bcc;
}

.reset-btn {
  border-color: #d9d9d9;
  color: #666;
}

.reset-btn:hover {
  border-color: #165DFF;
  color: #165DFF;
}

/* 创建战队按钮样式 */
.create-team-btn {
  background: #165DFF !important;
  border-color: #165DFF !important;
  color: #fff !important;
  transition: all 0.3s ease;
}

.create-team-btn:hover {
  background: #0e4bcc !important;
  border-color: #0e4bcc !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(22, 93, 255, 0.2);
}

/* 刷新按钮样式 */
.refresh-btn {
  background-color: #fff !important;
  color: #000 !important;
  border: none !important;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background-color: #90EE90 !important;
  color: #000 !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.refresh-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 创建战队弹窗样式 */
.create-team-form {
  padding: 16px 0;
}

.form-item {
  margin-bottom: 16px;
}

.form-row {
  display: flex;
  gap: 16px;
}

.form-row .form-item {
  flex: 1;
  margin-bottom: 16px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.required {
  color: #ff4d4f;
}

.subscription-settings {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.subscription-settings .form-item:last-child {
  margin-bottom: 0;
}

/* Logo上传样式 */
.logo-upload-container {
  position: relative;
}

.logo-upload-area {
  width: 100%;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.logo-upload-area:hover {
  border-color: #165DFF;
}

.logo-upload-placeholder {
  text-align: center;
}

.logo-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.upload-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(255, 255, 255, 0.9);
  padding: 8px 16px;
  border-radius: 4px;
  color: #165DFF;
  font-size: 14px;
}

/* 标签选择样式 */
:deep(.ant-select-multiple .ant-select-selection-item) {
  background: #165DFF;
  color: #fff;
  border: none;
}

:deep(.ant-select-multiple .ant-select-selection-item-remove) {
  color: #fff;
}

:deep(.ant-select-multiple .ant-select-selection-item-remove:hover) {
  color: #fff;
  background: rgba(255, 255, 255, 0.2);
}

/* 申请加入战队弹窗样式 */
.join-team-form {
  padding: 16px 0;
}

.team-info-preview {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.team-info-preview .flex {
  align-items: center;
}

.team-info-preview .w-12 {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
}

.team-info-preview .object-cover {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.join-team-form .form-item {
  margin-bottom: 20px;
}

.join-team-form .form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.join-team-form .required {
  color: #ff4d4f;
  margin-left: 4px;
}

.join-team-form .notice-info {
  margin-top: 20px;
}

/* 技能标签选择样式 */
:deep(.ant-select-multiple .ant-select-selection-item) {
  background: #165DFF;
  color: #fff;
  border: none;
  border-radius: 4px;
}

:deep(.ant-select-multiple .ant-select-selection-item-remove) {
  color: #fff;
}

:deep(.ant-select-multiple .ant-select-selection-item-remove:hover) {
  color: #fff;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
}

@media (max-width: 768px) {
  .search-filter-container {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input-group,
  .filter-group {
    min-width: auto;
  }

  .action-group {
    justify-content: center;
  }
}

/* 战队卡片样式 */
.team-card {
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
  cursor: pointer;
}

.team-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 16px 40px rgba(22, 93, 255, 0.15);
}

.team-logo-container {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.team-logo {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.team-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.team-card:hover .team-overlay {
  opacity: 1;
}

.team-card:hover .team-logo {
  transform: scale(1.1);
}

.team-info {
  padding: 1rem;
}

.team-name {
  font-size: 1.1rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 0.5rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.team-creator {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 0.75rem;
}

.team-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
}

.review-tag {
  font-size: 0.8rem;
}

.member-count {
  font-size: 0.9rem;
  color: #666;
}

.team-tags {
  margin-bottom: 0.75rem;
}

.team-tag {
  margin-right: 0.25rem;
  margin-bottom: 0.25rem;
  font-size: 0.8rem;
}

.team-description {
  font-size: 0.9rem;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  .carousel-item {
    height: 300px;
  }

  .carousel-content {
    padding: 1rem;
  }

  .carousel-content h3 {
    font-size: 1.2rem;
  }

  .carousel-content p {
    font-size: 0.9rem;
  }
}
</style>
